<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <script src="lib/tailwindcss3.4.16"></script>
    <link href="lib/Font Awesome Free 6.7.2-all.min.css" rel="stylesheet">
    <title>题库软件</title>
    <style>
        .question-label {
            width: 2.5rem; /* 增大题目标签外框宽度 */
            height: 2.5rem; /* 增大题目标签外框高度 */
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin: 0.25rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
            border: 1px solid #ccc;
            border-radius: 0; /* 默认无圆角 */
        }

        .question-label.current {
            background-color: #3b82f6;
            color: white;
            border-radius: 1.5rem; /* 被选中时变为圆角方形 */
        }

        .question-label.correct {
            background-color: #22c55e;
            color: white;
        }

        .question-label.incorrect {
            background-color: #ef4444;
            color: white;
        }

        #question-content {
            min-height: 200px;
            max-height: calc(100vh - 120px);
            overflow-y: auto;
            white-space: pre-wrap;
        }

        input[type="text"],
        textarea {
            border: 1px solid #ccc;
            padding: 0.5rem;
            margin-bottom: 0.5rem;
            height: 2.5rem;
        }

        textarea {
            height: 10rem;
        }

        input[type="radio"],
        input[type="checkbox"] {
            margin-right: 1rem;
            margin-bottom: 0.75rem;
        }

        #question-content h2 {
            margin-bottom: 0.5rem; /* 增加题目和答案选项之间的距离 */
            font-size: 1.25rem; /* 增加文字字号 */
        }

        #question-content label {
            font-size: 1.25rem; /* 1.125rem; 增加文字字号 */
        }

        /* 增大左侧题目类型之间的间距 */
        #question-types > div {
            margin-bottom: 1.5rem;
        }

        /* 自定义文件输入框样式 */
        .file-selection-group {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
        }

        .custom-file-input {
            position: relative;
            flex: 1;
            min-width: 120px;
        }

        .custom-file-input input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .custom-file-input label {
            display: block;
            padding: 0.5rem 1rem;
            background-color: #3b82f6;
            color: white;
            border-radius: 0.375rem;
            text-align: center;
            cursor: pointer;
            transition: background-color 0.3s ease;
            height: 100%;
            box-sizing: border-box;
        }

        .custom-file-input label:hover {
            background-color: #2563eb;
        }

        .custom-file-input label:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.5);
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }

        .action-buttons button {
            padding: 0.5rem 1rem;
            background-color: #4f46e5;
            color: white;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
            white-space: nowrap;
        }

        .action-buttons button:hover {
            background-color: #4338ca;
        }

        .action-buttons button:disabled {
            background-color: #a0aec0;
            cursor: not-allowed;
        }

        #save-btn {
            background-color: #22c55e;
        }

        #reset-btn {
            background-color: #ef4444;
        }

        #selected-file-path {
            padding: 0.5rem 0rem;
            font-size: 1rem;
            color: red;	
        }

        /* 新增样式，固定按钮容器 */
        #fixed-buttons {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
        }

        /* 调整左侧区域的内边距，避免按钮遮挡内容 */
        #question-types-container {
            padding-top: 1rem; /* 根据按钮容器高度调整 */
        }

        /* 图片样式 */
        .inline-image {
            display: inline-block;
            //max-width: 5rem;
            //height: auto;
            vertical-align: middle;
            cursor: zoom-in;
            margin: 0 0.2rem;
        }

        .block-image {
            display: block;
            max-width: 100%;
            height: auto;
            margin: 0.5rem 0;
            cursor: zoom-in;
        }

        /* 图片放大模态框 */
        .image-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .image-modal-content {
            max-width: 90%;
            max-height: 90%;
        }

        .image-modal-close {
            position: absolute;
            top: 20px;
            right: 30px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }

        /* 背题模式按钮样式 */
        #toggle-mode-btn {
            position: absolute;
            top: 1rem;
            right: 1rem;
            padding: 0.5rem 1rem;
            background-color: #8b5cf6;
            color: white;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
            z-index: 10;
        }

        #toggle-mode-btn:hover {
            background-color: #7c3aed;
        }
    </style>
</head>

<body class="bg-gray-100">
    <!-- 图片放大模态框 -->
    <div id="imageModal" class="image-modal">
        <span class="image-modal-close">&times;</span>
        <img id="modalImage" class="image-modal-content">
    </div>

    <div class="flex h-screen">
        <!-- 左侧题目类型和序号区域 -->
        <div class="w-1/4 bg-white p-4 overflow-y-auto" id="question-types-container">
            <div id="question-types"></div>
        </div>
        <!-- 右侧题目内容区域 -->
        <div class="w-3/4 bg-gray-200 p-4 relative">
            <!-- 新增切换模式按钮 -->
            <button id="toggle-mode-btn">切换为背题模式</button>
            <!-- 新增固定按钮容器 -->
            <div id="fixed-buttons">
                <div class="file-selection-group">
                    <div class="custom-file-input">
                        <input type="file" id="question-file-input" accept=".txt,.json">
                        <label for="question-file-input">选择题目数据文件</label>
                    </div>
                    <div class="action-buttons">
                        <button id="save-btn">保存状态</button>
                        <button id="reset-btn">全部重置</button>
                    </div>
                    <div id="selected-file-path"></div>
                </div>
            </div>
            <div id="question-content" class="bg-white p-4 rounded shadow mb-4 overflow-y-auto"></div>
            <div class="flex justify-start space-x-2">
                <button id="confirm-btn" class="bg-blue-500 text-white px-4 py-2 rounded">确定</button>
                <button id="clear-btn" class="bg-yellow-500 text-white px-4 py-2 rounded">清空</button>
                <button id="prev-btn" class="bg-gray-500 text-white px-4 py-2 rounded">上一题</button>
                <button id="next-btn" class="bg-gray-500 text-white px-4 py-2 rounded">下一题</button>
            </div>
        </div>
    </div>

    <script>
        let currentType;  // 默认 currentType 为 questions 的第一个 key 值
        let currentIndex = 0;
        let answered = {};
        let userAnswers = {}; // 用于存储用户的答案
        const confirmBtn = document.getElementById('confirm-btn');
        const clearBtn = document.getElementById('clear-btn');
        const questionTypesContainer = document.getElementById('question-types-container');
        const questionFileInput = document.getElementById('question-file-input');
        const selectedFilePathDiv = document.getElementById('selected-file-path');
        const saveBtn = document.getElementById('save-btn');
        const resetBtn = document.getElementById('reset-btn');
        let questions = {};
        let selectedFilePath = '';
        const SAVE_KEY = 'questionnaire_state';
        const imageModal = document.getElementById('imageModal');
        const modalImage = document.getElementById('modalImage');
        const modalClose = document.querySelector('.image-modal-close');
        const toggleModeBtn = document.getElementById('toggle-mode-btn');
        let isReviewMode = false; // 新增变量，用于记录当前模式

        // 图片点击放大功能
        function setupImageZoom() {
            document.querySelectorAll('.inline-image, .block-image').forEach(img => {
                img.addEventListener('click', function() {
                    modalImage.src = this.src;
                    imageModal.style.display = 'flex';
                });
            });
        }

        // 关闭模态框
        modalClose.addEventListener('click', function() {
            imageModal.style.display = 'none';
        });

        // 点击模态框外部关闭
        imageModal.addEventListener('click', function(e) {
            if (e.target === imageModal) {
                imageModal.style.display = 'none';
            }
        });

        // 检查是否有保存的状态
        const savedState = localStorage.getItem(SAVE_KEY);
        if (savedState) {
            const { 
                savedQuestions, 
                savedCurrentType, 
                savedCurrentIndex, 
                savedAnswered, 
                savedUserAnswers,
                savedFilePath,
                savedIsReviewMode
            } = JSON.parse(savedState);
            
            questions = savedQuestions;
            currentType = savedCurrentType;
            currentIndex = savedCurrentIndex;
            answered = savedAnswered;
            userAnswers = savedUserAnswers;
            selectedFilePath = savedFilePath;
            isReviewMode = savedIsReviewMode || false;
            
            if (selectedFilePath) {
                selectedFilePathDiv.textContent = `已选择文件: ${selectedFilePath}`;
            }
            
            initQuestionTypes();
            showQuestion();
            updateToggleModeButton();
        }

        // 更新切换模式按钮文本
        function updateToggleModeButton() {
            toggleModeBtn.textContent = isReviewMode ? '切换为答题模式' : '切换为背题模式';
        }

        // 切换背题/答题模式
        function toggleReviewMode() {
            isReviewMode = !isReviewMode;
            updateToggleModeButton();
            
            if (isReviewMode) {
                // 进入背题模式，加载所有答案
                loadAllAnswers();
            } else {
                // 退出背题模式，清空所有答案
                resetAllAnswers();
            }
            
            // 保存当前状态
            //saveState();
            
            // 刷新当前题目显示
            showQuestion();
        }

        // 加载所有答案（背题模式）
        function loadAllAnswers() {
            if (!questions || Object.keys(questions).length === 0) return;
            
            for (const type in questions) {
                for (let i = 0; i < questions[type].length; i++) {
                    const question = questions[type][i];
                    const key = `${type}-${i}`;
                    
                    // 存储正确答案
                    if (Array.isArray(question.answer)) {
                        userAnswers[key] = [...question.answer];
                    } else {
                        userAnswers[key] = question.answer;
                    }
                    
                    // 标记为已答且正确
                    answered[key] = true;
                }
            }
        }

        // 清空所有答案（退出背题模式）
        function resetAllAnswers() {
            userAnswers = {};
            answered = {};
            
            // 清除所有标签的状态
            const labels = document.querySelectorAll('.question-label');
            labels.forEach(label => {
                label.classList.remove('correct', 'incorrect');
            });
        }

        questionFileInput.addEventListener('change', function (event) {
            const file = event.target.files[0];
            if (file) {
                selectedFilePath = file.path || file.name;
                selectedFilePathDiv.textContent = `已选择文件: ${selectedFilePath}`;
                const reader = new FileReader();
                reader.onload = function (e) {
                    try {
                        questions = JSON.parse(e.target.result);
                        currentType = Object.keys(questions)[0];  // 默认 currentType 为 questions 的第一个 key 值
                        currentIndex = 0; 
                        // 清空作答记录
                        answered = {};
                        userAnswers = {};
                        isReviewMode = false;
                        updateToggleModeButton();
                        initQuestionTypes();
                        showQuestion();
                    } catch (error) {
                        alert('解析文件内容时出错，请确保文件内容为有效的 JSON 格式。');
                    }
                };
                reader.readAsText(file);
            } else {
                if (selectedFilePath) {
                    selectedFilePathDiv.textContent = `已选择文件: ${selectedFilePath}`;
                } else {
                    selectedFilePathDiv.textContent = '';
                }
            }
        });

        // 初始化左侧题目类型和序号
        function initQuestionTypes() {
            const questionTypesDiv = document.getElementById('question-types');
            questionTypesDiv.innerHTML = '';
            for (const type in questions) {
                const typeDiv = document.createElement('div');
                typeDiv.innerHTML = `<h3 class="text-lg font-bold mb-2">${type}</h3>`;
                for (let i = 0; i < questions[type].length; i++) {
                    const label = document.createElement('span');
                    label.classList.add('question-label');
                    label.textContent = i + 1;
                    label.dataset.type = type;
                    label.dataset.index = i;
                    label.addEventListener('click', () => {
                        currentType = type;
                        currentIndex = i;
                        showQuestion();
                    });
                    typeDiv.appendChild(label);
                }
                questionTypesDiv.appendChild(typeDiv);
            }
        }

        // 处理题目中的图片标记
        function processImages(questionText) {
            // 处理行内图片格式：[图片:图片URL##style=]
            questionText = questionText.replace(/\[图片:(.*?)##style=(.*?)\]/g, '<img src="$1" style="$2" class="inline-image" alt="行内图片">');
			
			// 处理行内图片格式：[图片:图片URL##width=##height=]
            questionText = questionText.replace(/\[图片:(.*?)##width=(.*?)##height=(.*?)\]/g, '<img src="$1" style="width:$2cm; height:$3cm" class="inline-image" alt="行内图片">');
            
            // 处理不带尺寸的行内图片格式：[图片:图片URL]
            questionText = questionText.replace(
                /\[图片:(.*?)\]/g, 
                '<img src="$1" class="inline-image" alt="行内图片">'
            );
            
            return questionText;
        }

        // 显示当前题目
        function showQuestion() {
            const questionContentDiv = document.getElementById('question-content');
            questionContentDiv.innerHTML = '';

            if (!questions || !questions[currentType]) {
                return;
            }

            const question = questions[currentType][currentIndex];
            const questionTitle = document.createElement('h2');
            
            // 处理题目中的图片
            const processedQuestion = processImages(question.question);
            questionTitle.innerHTML = `${currentType}（第 ${currentIndex + 1} 题）：${processedQuestion}`;
            questionContentDiv.appendChild(questionTitle);

            if (currentType === '单选题' || currentType === '多选题') {
                for (let i = 0; i < question.options.length; i++) {
                    const input = document.createElement('input');
                    input.type = currentType === '单选题' ? 'radio' : 'checkbox';
                    input.name = 'option';
                    input.value = String.fromCharCode(65 + i);
                    const label = document.createElement('label');
                    
                    // 处理选项中的图片
                    const processedOption = processImages(question.options[i]);
                    label.innerHTML = processedOption;
                    
                    label.addEventListener('click', () => {
                        input.click();
                    });
                    input.addEventListener('change', checkAnswerStatus);
                    questionContentDiv.appendChild(input);
                    questionContentDiv.appendChild(label);
                    questionContentDiv.appendChild(document.createElement('br'));

                    // 恢复答案选项的选中状态
                    if (userAnswers[`${currentType}-${currentIndex}`]) {
                        if (Array.isArray(userAnswers[`${currentType}-${currentIndex}`])) {
                            input.checked = userAnswers[`${currentType}-${currentIndex}`].includes(input.value);
                        } else {
                            input.checked = userAnswers[`${currentType}-${currentIndex}`] === input.value;
                        }
                    }
                }
            } else if (currentType === '填空题') {
                const blanks = question.question.match(/______/g).length;
                for (let i = 0; i < blanks; i++) {
                    const input = document.createElement('input');
                    input.type = 'text';
                    input.style.width = '100%';
                    input.name = `blank-${i}`;
                    input.addEventListener('input', checkAnswerStatus);
                    questionContentDiv.appendChild(input);
                    questionContentDiv.appendChild(document.createElement('br'));

                    // 恢复输入框中的内容
                    if (userAnswers[`${currentType}-${currentIndex}`] && userAnswers[`${currentType}-${currentIndex}`][i]) {
                        input.value = userAnswers[`${currentType}-${currentIndex}`][i];
                    }
                }
                //焦点默认在第一个框中
                const inputs = document.querySelectorAll('input[name^="blank-"]');
                if (inputs.length > 0) {
                    inputs[0].focus();
                }
            } else if (currentType === '判断题') {
                const trueInput = document.createElement('input');
                trueInput.type = 'radio';
                trueInput.name = 'option';
                trueInput.value = '正确';
                const trueLabel = document.createElement('label');
                trueLabel.textContent = '正确';
                trueLabel.addEventListener('click', () => {
                    trueInput.click();
                });
                const falseInput = document.createElement('input');
                falseInput.type = 'radio';
                falseInput.name = 'option';
                falseInput.value = '错误';
                const falseLabel = document.createElement('label');
                falseLabel.textContent = '错误';
                falseLabel.addEventListener('click', () => {
                    falseInput.click();
                });
                trueInput.addEventListener('change', checkAnswerStatus);
                falseInput.addEventListener('change', checkAnswerStatus);
                questionContentDiv.appendChild(trueInput);
                questionContentDiv.appendChild(trueLabel);
                questionContentDiv.appendChild(document.createElement('br'));
                questionContentDiv.appendChild(falseInput);
                questionContentDiv.appendChild(falseLabel);

                // 恢复答案选项的选中状态
                if (userAnswers[`${currentType}-${currentIndex}`] !== undefined) {
                    trueInput.checked = userAnswers[`${currentType}-${currentIndex}`] === '正确';
                    falseInput.checked = userAnswers[`${currentType}-${currentIndex}`] === '错误';
                }
            } else if (currentType === '简答题') {
                const textarea = document.createElement('textarea');
                textarea.style.width = '100%';
                textarea.name = 'answer';
                textarea.addEventListener('input', checkAnswerStatus);
                questionContentDiv.appendChild(textarea);
                textarea.classList.add('p-2');  //多行文本框设置边距
                textarea.focus();

                // 恢复文本框中的内容
                if (userAnswers[`${currentType}-${currentIndex}`]) {
                    textarea.value = userAnswers[`${currentType}-${currentIndex}`];
                }
            }

            // 高亮当前题目标签
            const labels = document.querySelectorAll('.question-label');
            labels.forEach(label => {
                label.classList.remove('current', 'correct', 'incorrect');
                if (label.dataset.type === currentType && parseInt(label.dataset.index) === currentIndex) {
                    label.classList.add('current');
                    // 确保当前题对应的左侧标签始终可见
                    const rect = label.getBoundingClientRect();
                    const containerRect = questionTypesContainer.getBoundingClientRect();
                    if (rect.top < containerRect.top || rect.bottom > containerRect.bottom) {
                        label.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }
                }
                if (answered[`${label.dataset.type}-${label.dataset.index}`] !== undefined) {
                    if (answered[`${label.dataset.type}-${label.dataset.index}`]) {
                        label.classList.add('correct');
                    } else {
                        label.classList.add('incorrect');
                    }
                }
            });

            // 显示已回答状态
            if (answered[`${currentType}-${currentIndex}`] !== undefined) {
                const result = answered[`${currentType}-${currentIndex}`];
                const resultDiv = document.createElement('div');
                if (result) {
                    resultDiv.textContent = '回答正确！';
                    resultDiv.classList.add('text-green-500');
                } else {
                    resultDiv.textContent = `回答错误，正确答案是：${Array.isArray(question.answer) ? question.answer.join(', ') : question.answer}`;
                    resultDiv.classList.add('text-red-500');
                }
                questionContentDiv.appendChild(resultDiv);
            }

            // 设置图片点击放大功能
            setTimeout(setupImageZoom, 0);

            checkAnswerStatus();
        }

        // 检查是否作答
        function checkAnswerStatus() {
            let isAnswered = false;
            if (currentType === '单选题' || currentType === '判断题') {
                const inputs = document.querySelectorAll('input[name="option"]:checked');
                isAnswered = inputs.length > 0;
            } else if (currentType === '多选题') {
                const inputs = document.querySelectorAll('input[name="option"]:checked');
                isAnswered = inputs.length > 0;
            } else if (currentType === '填空题') {
                const inputs = document.querySelectorAll('input[name^="blank-"]');
                isAnswered = Array.from(inputs).every(input => input.value.trim() !== '');
            } else if (currentType === '简答题') {
                const textarea = document.querySelector('textarea[name="answer"]');
                isAnswered = textarea.value.trim() !== '';
            }
        }

        // 确认答案
        function confirmAnswer() {
            const question = questions[currentType][currentIndex];
            let userAnswer;
            if (currentType === '单选题' || currentType === '判断题') {
                const inputs = document.querySelectorAll('input[name="option"]:checked');
                userAnswer = inputs.length > 0 ? inputs[0].value : null;
            } else if (currentType === '多选题') {
                const inputs = document.querySelectorAll('input[name="option"]:checked');
                userAnswer = [];
                inputs.forEach(input => userAnswer.push(input.value));
            } else if (currentType === '填空题') {
                const inputs = document.querySelectorAll('input[name^="blank-"]');
                userAnswer = [];
                inputs.forEach(input => userAnswer.push(input.value.trim())); // 添加trim()去除空格
            } else if (currentType === '简答题') {
                const textarea = document.querySelector('textarea[name="answer"]');
                userAnswer = textarea.value;
            }

            // 存储用户的答案
            userAnswers[`${currentType}-${currentIndex}`] = userAnswer;

            let isCorrect;
            if (Array.isArray(question.answer)) {
                // 对于填空题，逐个比较每个空的答案
                if (currentType === '填空题') {
                    isCorrect = true;
                    for (let i = 0; i < question.answer.length; i++) {
                        if (userAnswer[i] !== question.answer[i]) {
                            isCorrect = false;
                            break;
                        }
                    }
                } else {
                    isCorrect = JSON.stringify(userAnswer.sort()) === JSON.stringify(question.answer.sort());
                }
            } else {
                isCorrect = userAnswer === question.answer;
            }

            answered[`${currentType}-${currentIndex}`] = isCorrect;

            const label = document.querySelector(`.question-label[data-type="${currentType}"][data-index="${currentIndex}"]`);
            if (isCorrect) {
                label.classList.add('correct');
                label.classList.remove('incorrect');
            } else {
                label.classList.add('incorrect');
                label.classList.remove('correct');
            }

            showQuestion();

            // 不论正确与否，都自动切换到下一题
            if (currentIndex < questions[currentType].length - 1) {
                currentIndex++;
            } else {
                const types = Object.keys(questions);
                const currentTypeIndex = types.indexOf(currentType);
                if (currentTypeIndex < types.length - 1) {
                    currentType = types[currentTypeIndex + 1];
                    currentIndex = 0;
                }
            }
            showQuestion();
        }

        // 清空答案
        function clearAnswer() {
            userAnswers[`${currentType}-${currentIndex}`] = null;
            answered[`${currentType}-${currentIndex}`] = undefined;
            const label = document.querySelector(`.question-label[data-type="${currentType}"][data-index="${currentIndex}"]`);
            label.classList.remove('correct', 'incorrect');
            showQuestion();
        }

        // 上一题
        function prevQuestion() {
            if (currentIndex > 0) {
                currentIndex--;
            } else {
                const types = Object.keys(questions);
                const currentTypeIndex = types.indexOf(currentType);
                if (currentTypeIndex > 0) {
                    currentType = types[currentTypeIndex - 1];
                    currentIndex = questions[currentType].length - 1;
                }
            }
            showQuestion();
        }

        // 下一题
        function nextQuestion() {
            if (currentIndex < questions[currentType].length - 1) {
                currentIndex++;
            } else {
                const types = Object.keys(questions);
                const currentTypeIndex = types.indexOf(currentType);
                if (currentTypeIndex < types.length - 1) {
                    currentType = types[currentTypeIndex + 1];
                    currentIndex = 0;
                }
            }
            showQuestion();
        }

        // 保存当前答题状态
        function saveState() {
            if (!questions || Object.keys(questions).length === 0) {
                alert('请先选择题目数据文件');
                return;
            }
            
            const state = {
                savedQuestions: questions,
                savedCurrentType: currentType,
                savedCurrentIndex: currentIndex,
                savedAnswered: answered,
                savedUserAnswers: userAnswers,
                savedFilePath: selectedFilePath,
                savedIsReviewMode: isReviewMode
            };
            
            localStorage.setItem(SAVE_KEY, JSON.stringify(state));
            alert('答题状态已保存！');
        }

        // 重置所有答案，恢复初始状态
        function resetAll() {
            if (!questions || Object.keys(questions).length === 0) {
                alert('请先选择题目数据文件');
                return;
            }
            
            if (confirm('确定要清空所有答案，恢复初始状态吗？')) {
                // 保留题目数据和当前类型，重置其他状态
                currentIndex = 0;
                answered = {};
                userAnswers = {};
                isReviewMode = false;
                updateToggleModeButton();
                
                // 清除所有标签的状态
                const labels = document.querySelectorAll('.question-label');
                labels.forEach(label => {
                    label.classList.remove('current', 'correct', 'incorrect');
                });
                  
                // 清除本地存储的状态
                localStorage.removeItem(SAVE_KEY);
                
                // 重置为第一个题目
                currentType = Object.keys(questions)[0];
                currentIndex = 0;
                showQuestion();
            }
        }

        // 监听键盘事件
        document.addEventListener('keydown', function (event) {
            // 只有当questions有数据时才处理回车和空格键
            if (Object.keys(questions).length > 0) {
                if ((event.key === 'Enter' || event.code === 'Space') && (currentType === '判断题' || currentType === '单选题' || currentType === '多选题')) {
                    event.preventDefault(); // 阻止默认行为
                    confirmAnswer();
                } else if ((event.key === 'Enter') && (currentType === '填空题' || currentType === '简答题')) {
                    event.preventDefault(); // 阻止默认行为
                    confirmAnswer();
                } else if (event.key === 'Escape') {
                    event.preventDefault();
                    clearAnswer();
                } else if (currentType === '判断题' && (event.key === '1' || event.key === '2')) {
                    event.preventDefault();
                    const option = event.key === '1' ? '正确' : '错误';
                    const inputs = document.querySelectorAll('input[name="option"]');
                    inputs.forEach(input => {
                        if (input.value === option) {
                            input.checked = true;
                            checkAnswerStatus();
                        }
                    });
                } else if ((currentType === '单选题' || currentType === '多选题') && /^[1-9]$/.test(event.key)) {
                    event.preventDefault();
                    const index = parseInt(event.key) - 1;
                    const option = String.fromCharCode(65 + index);
                    const inputs = document.querySelectorAll('input[name="option"]');
                    inputs.forEach(input => {
                        if (input.value === option) {
                            if (currentType === '单选题') {
                                inputs.forEach(inp => inp.checked = false);
                            }
                            input.checked = !input.checked;
                            checkAnswerStatus();
                        }
                    });
                }
            }

            // 左右箭头键不受questions数据影响
            if (event.key === 'ArrowLeft') {
                event.preventDefault();
                prevQuestion();
            } else if (event.key === 'ArrowRight') {
                event.preventDefault();
                nextQuestion();
            }
        });

        // 绑定按钮事件
        confirmBtn.addEventListener('click', confirmAnswer);
        clearBtn.addEventListener('click', clearAnswer);
        const prevBtn = document.getElementById('prev-btn');
        prevBtn.addEventListener('click', prevQuestion);
        const nextBtn = document.getElementById('next-btn');
        nextBtn.addEventListener('click', nextQuestion);
        saveBtn.addEventListener('click', saveState);
        resetBtn.addEventListener('click', resetAll);
        toggleModeBtn.addEventListener('click', toggleReviewMode);
    </script>
</body>

</html>
